package com.czy.owner.ui.garage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.CarBrandAttrAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarBrandModel;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.PageTitleView;
import com.czy.owner.widget.RoundImageView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SelCarOtherAttrActivity extends BaseActivity {

    PageTitleView pageTitle;
    @BindView(R.id.tv_page_title_center)
    TextView tvPageTitleCenter;
    @BindView(R.id.btn_page_title_center)
    Button btnPageTitleCenter;
    @BindView(R.id.btn_page_title_left)
    Button btnPageTitleLeft;
    @BindView(R.id.btn_page_title_right)
    Button btnPageTitleRight;
    @BindView(R.id.rl_page_title)
    RelativeLayout rlPageTitle;
    @BindView(R.id.iv_car_brand_logo)
    RoundImageView ivCarBrandLogo;
    @BindView(R.id.tv_car_brand_name)
    TextView tvCarBrandName;
    @BindView(R.id.tv_title_sel_pl)
    TextView tvTitleSelPl;
    @BindView(R.id.iv_middle_arrow)
    ImageView ivMiddleArrow;
    @BindView(R.id.tv_title_sel_nf)
    TextView tvTitleSelNf;
    @BindView(R.id.rv_other_attr)
    RecyclerView rvOtherAttr;

    public static final String FIRST_LIST_DATA = "first_list_data";
    public static final String IS_NEED_RESULT_DATA = "is_need_result_data";
    private Context mContext;
    private CarBrandAttrAdapter firstAdapter;
    private CarBrandAttrAdapter secondAdapter;
    private boolean isSecond = false;
    private CarBrandModel selectedCarModel ;
    private List<CarBrandModel> firstListData;
    private long selectedPLId ;
    private String selectedPLName ;
    private long selectedNFId ;
    private boolean isNeedReturnResult;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_sel_car_other_attr;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        mContext = this;
        pageTitle = new PageTitleView((RelativeLayout) findViewById(R.id.rl_page_title), "自助选车", true);
        pageTitle.getLeftButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealBack();
            }
        });
        selectedCarModel = (CarBrandModel) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
        firstListData = (List<CarBrandModel>) getIntent().getSerializableExtra(FIRST_LIST_DATA);
        isNeedReturnResult = getIntent().getBooleanExtra(IS_NEED_RESULT_DATA,false);
        if(selectedCarModel != null) {
            tvCarBrandName.setText(selectedCarModel.getChName());
            x.image().bind(ivCarBrandLogo, selectedCarModel.getImageSrc(), new Callback.CommonCallback<Drawable>() {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ivCarBrandLogo.setImageResource(R.mipmap.default_icon);
                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException cex) {
                    ivCarBrandLogo.setImageResource(R.mipmap.default_icon);
                }

                @Override
                public void onSuccess(Drawable result) {
                }
            });
            firstAdapter = new CarBrandAttrAdapter(mContext);
            secondAdapter = new CarBrandAttrAdapter(mContext);
            rvOtherAttr.setLayoutManager(new LinearLayoutManager(mContext));
            rvOtherAttr.setAdapter(firstAdapter);
            rvOtherAttr.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
//            getPLData(selectedCarModel.getCarBrandId());
            if(firstListData != null) {
                firstAdapter.addAll(firstListData);
            }
            firstAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<CarBrandModel>() {
                @Override
                public void onItemClick(View view, int position, CarBrandModel o) {
                    getNFData(o);
                }
            });

            secondAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<CarBrandModel>() {
                @Override
                public void onItemClick(View view, int position, CarBrandModel o) {
                    MyLog.d("RAVEN","need result = " + isNeedReturnResult);
                    if(isNeedReturnResult){
                        Intent intent = new Intent();
                        selectedCarModel.setCarBrandId(o.getCarBrandId());
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
                        intent.putExtra("selected_car_pl", selectedPLName);
                        intent.putExtra("selected_car_nf", o.getChName());
                        setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                        finish();
                    } else {
                        MyLog.d("RAVEN","第五级数据选中，跳转。。。。EditCar");
                        Intent intent = new Intent(mContext, EditCarActivity.class);
                        selectedCarModel.setCarBrandId(o.getCarBrandId());
                        intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
                        startActivityForResult(intent, 0);
                    }
                }
            });
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(isSecond){
                rvOtherAttr.setAdapter(firstAdapter);
                ivMiddleArrow.setVisibility(View.GONE);
                tvTitleSelNf.setVisibility(View.GONE);
                tvTitleSelPl.setText("选择发动机排量");
                tvTitleSelPl.setTextColor(ContextCompat.getColor(mContext,R.color.appThemeTitleColor));
                isSecond = false;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void dealBack(){
        if(isSecond){
            rvOtherAttr.setAdapter(firstAdapter);
            ivMiddleArrow.setVisibility(View.GONE);
            tvTitleSelNf.setVisibility(View.GONE);
            tvTitleSelPl.setText("选择发动机排量");
            tvTitleSelPl.setTextColor(ContextCompat.getColor(mContext,R.color.appThemeTitleColor));
            isSecond = false;
        }else {
            onBackPressed();
        }
    }


    @Override
    protected void updateViews() {

    }

    private void getNFData(final CarBrandModel model){
        secondAdapter.clear();
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_ALL_ATTR);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("carBrandId", "" + model.getCarBrandId());
        MyLog.d("RAVEN","params = " + params);
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.d("RAVEN","result = " + result);
                String data = PhoneUtils.checkResponseFlag((Activity) mContext, result);
                if (data != null) {
                    try {
                        Gson gson = new GsonBuilder().create();
                        List<CarBrandModel> carNF = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                        }.getType());
                        /**有第五级数据，显示出来*/
                        if(carNF != null && carNF.size() > 0){//年份不为空
                            tvTitleSelPl.setText("" + model.getChName());
                            tvTitleSelPl.setTextColor(ContextCompat.getColor(mContext,R.color.orange));
                            ivMiddleArrow.setVisibility(View.VISIBLE);
                            tvTitleSelNf.setVisibility(View.VISIBLE);
                            isSecond = true;
                            selectedPLId = model.getCarBrandId();
                            selectedPLName = model.getChName();
                            secondAdapter.addAll(carNF);
                            rvOtherAttr.setAdapter(secondAdapter);
                        }else {//没有第五级别数据，直接做处理
                            if(isNeedReturnResult){
                                Intent intent = new Intent();
                                selectedCarModel.setCarBrandId(model.getCarBrandId());
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
                                intent.putExtra("selected_car_pl", model.getChName());
                                setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                                finish();
                            } else {
                                MyLog.d("RAVEN","处理第四级别选中");
                                Intent intent = new Intent(mContext, EditCarActivity.class);
                                selectedCarModel.setCarBrandId(model.getCarBrandId());
                                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
                                startActivityForResult(intent, 0);
                            }
                        }

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
            finish();
        }
    }
}
